package handlers

import (
	"github.com/gin-gonic/gin"
	"news-hubs/models"
	"news-hubs/pkg"
)

func Login(c *gin.Context) {
	tel := c.PostForm("tel")
	password := pkg.Md5(c.PostForm("password"))
	var user = models.User{
		Tel:      tel,
		Password: password,
	}
	if tel == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}
	err := models.DB.Create(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "注册失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
}

func Logon(c *gin.Context) {
	tel := c.Query("tel")
	password := c.Query("password")
	user_id := c.PostForm("user_id")
	var user = models.User{}
	err := models.DB.Where("tel = ? and password=?", tel, pkg.Md5(password)).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在,登陆失败",
		})
		return
	}
	token := pkg.TokenHandler(user_id)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": token,
	})
}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	user_id := c.PostForm("user_id")
	var news = models.New{
		Title:   title,
		Content: content,
		Img:     img,
	}
	if user_id == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户未登录",
		})
		return
	}
	err := models.DB.Create(&news).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
		"data": news,
	})
}
